#-*- coding:utf-8 -*-
'''
插入指定页面，如果没有指出插入源，则插入空白页面
'''
import os
import sys
import shutil
from datetime import datetime as dt
from ShortMessage import alert_module_pyMuPDF
from ShortMessage import MSG,test_file_exists,test_pymupdf_imported,message_finished,message_started
from muSplitPdf import muSplitPdfObject
from muCropPdf import muCropPdfObject
from ArgumentParse import getMakePrintablePdfParseResult
from UtilFunction import getPageRange
FITZ_IMPORT_FAIL = False
try:
    import fitz 
except:
    FITZ_IMPORT_FAIL =True

def muInsertPagePdfFile(input_pdf,output_pdf,page_index,page_source_pdf=None,page_source_index=-1):
    doc = muInsertPagePdfObject(input_pdf,page_index,page_source_pdf,page_source_index)
    try:
        doc.save(output_pdf)
        MSG("Save To PDF [%s]"%output_pdf)
    except:
        MSG("Fail When Save File [%s]"%output_pdf)
    message_finished()

def muInsertPagePdfObject(input_pdf,page_index,page_source_pdf=None,page_source_index=-1):
    if type(input_pdf) == type(""):
        input_pdf = fitz.open()

    if page_source_pdf:
        input_pdf.insertPDF(page_source_pdf,page_source_index-1,page_source_index-1)
    else:
        r = input_pdf.loadPage(0).rect
        input_pdf.insertPage(page_index,width=r.width,height=r.height)
    return input_pdf

if __name__ == "__main__":
    if FITZ_IMPORT_FAIL:
        alert_module_pyMuPDF()
    else:
        pass